package middlerware

import (
	"gin_cli/pkg/cache"
	"gin_cli/pkg/e"
	"gin_cli/pkg/util"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		token = string([]byte(token)[7:])
		now := time.Now().Unix()
		result, err := util.ParseToken(token)
		if err != nil {
			c.JSON(
				http.StatusNonAuthoritativeInfo,
				e.GetResponse(e.SUCCESS, "token错误"),
			)
			c.Abort()
			return
		}

		exp := int64(result["exp"].(float64))
		if exp < now {
			c.JSON(
				http.StatusNonAuthoritativeInfo,
				e.GetResponse(e.SUCCESS, "token过期"),
			)
			c.Abort()
			return
		}

		data := result["data"].(map[string]interface{})
		id := int64(data["id"].(float64))
		idStr := strconv.FormatInt(id, 10)
		cacheNonceStr, err := cache.Get(idStr)
		nonceStr := result["nonceStr"].(string)
		if err != nil || cacheNonceStr != nonceStr {
			c.JSON(
				http.StatusNonAuthoritativeInfo,
				e.GetResponse(e.SUCCESS, "nonceStr 无效"),
			)
			c.Abort()
			return
		}
		social := int64(data["social"].(float64))
		c.Set("id", id)
		c.Set("type", data["type"])
		c.Set("social", social)
		c.Next()
	}
}
